﻿@using ST.Torch.WebApi.Web.Core;
@inherits UtilRazorPage<object>
@{
    Layout = "~/Views/Shared/__ComponentLayout.cshtml";
    string randomId = Guid.NewGuid().ToString();
}
<div style="padding: 5px;">
    <div class="layui-card">
        <div class="layui-card-body">
        <table class="layui-hide" id="tableEle_@randomId" lay-filter="tableEle_@randomId"></table>
        </div>
    </div>
</div>

@section footer
{
    <script type="text/html" id="toolbarDemo_@randomId">
         <div style="display:flex">
             <div style="flex:1">
                  <div class="layui-btn-container">
                      <button class="layui-btn layui-btn-sm" lay-event="AddData" lay-permission="GeneralAddDataPerm"><i class="layui-icon layui-icon-add-circle"></i>@L("新增")</button>
                      <button class="layui-btn layui-btn-sm" lay-event="ExportExcelData" lay-permission="GeneralExportDataPerm"> <i class="layui-icon layui-icon-download-circle"></i>@L("导出excel")</button>
                      <button class="layui-btn layui-btn-sm" lay-event="DelData" lay-permission="GeneralDelDataPerm"> <i class="layui-icon layui-icon-delete"></i>@L("删除")</button>
                </div>
             </div>
            <div style="width:200px;display:flex">
                 <input type="text"  id="Querykey_@randomId" placeholder="" style="display: inline-block;height: 30px; line-height: 30px;margin-right:5px" class="layui-input">
                 <button class="layui-btn layui-btn-sm" lay-event="QueryData">@L("查询")</button>
            </div>

        </div>
    </script>
    <script type="text/html" id="barDemo_@randomId">
        <div class="layui-clear-space">
          <button class="layui-btn layui-btn-xs" lay-event="edit" lay-permission="GeneralEditDataPerm">@L("编辑")</button>

          
          <a class="layui-btn layui-btn-xs" lay-event="more">
                @L("更多")
            <i class="layui-icon layui-icon-down"></i>
          </a>
        </div>
    </script>

    <script type="text/html" id="GiftImgUrl_@randomId">
        <img src="{{ FileHttpApiUrl+ ''+d.GiftImgUrl}}" style="width:38px;height:38px" />
    </script>
    <script>

        layui.use(['table', 'toast', 'dropdown', 'jquery', 'upload', 'element'], function () {
            var  table = layui.table;
            var dropdown = layui.dropdown;
            var form = layui.form;
            var toast = layui.toast;
            var upload = layui.upload;
            var $ = layui.jquery;
            var element = layui.element;
           
            // 创建渲染实例
            table.render({
                elem: '#tableEle_@randomId',
                url: '/api/D_Gift/GetDataPagedList', // 此处为静态模拟数据，实际使用时需换成真实接口
                method: 'post',//如果无需自定义HTTP类型，可不加该参数
                toolbar: '#toolbarDemo_@randomId',
                defaultToolbar: ['filter', 'exports', 'print', {
                    title: '提示',
                    layEvent: 'LAYTABLE_TIPS',
                    icon: 'layui-icon-tips'
                }],
                height: 'full-135', // 最大高度减去其他容器已占有的高度差
                limit: 20,//注意：请务必确保 limit 参数（默认：10）是与你服务端限定的数据条数一致
                css: [ // 重设当前表格样式
                    '.layui-table-tool-temp{padding-right: 145px;}'
                ].join(''),
                cellMinWidth: 80,
                //totalRow: true, // 开启合计行
                page: true,
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    
                    { field: 'Name', title: '@L("礼品名称")' },
                    { field: 'GiftImgUrl', title: '@L("礼品图片")' , templet: '#GiftImgUrl_@randomId'},
                    { field: 'Number', title: '@L("礼品数量")' },
                    { field: 'RemainingNumber', title: '@L("剩余数量")' },
                    { fixed: 'right', title: '@L("操作")', width: 150, minWidth: 150, toolbar: '#barDemo_@randomId' }
                ]],
                parseData: function (res) {
                    if(res.StatusCode!=200){
                        return{
                            "msg": res.Errors,
                          };
                     }
                    console.log(res)
                    return {
                        "count": res.Data.TotalCount,
                        'statusCode': res.StatusCode,
                        'data': res.Data.Items
                    };
                },
                response: {
                    statusName: 'statusCode',
                    statusCode: 200
                },
                done: function () {
                    var id = this.id;
                    permissionUI();
                },
                error: function (res, msg) {
                    console.log(res, msg)
                }
            });

            var progressTime = null;
            var progressKey = 'progressKey_@randomId)';
            console.log("---.jpg|png|gif----!")
            // 工具栏事件
            table.on('toolbar(tableEle_@randomId)', function (obj) {
                var id = obj.config.id;
                var checkStatus = table.checkStatus(id);
                var othis = lay(this);
                switch (obj.event) {
                    case 'QueryData':
                        var key = $("#Querykey_@randomId").val();
                        table.reloadData('tableEle_@randomId', {
                            where: {
                                key: key,
                            },
                            page: { curr: 1, limit: 20 } // 重新指向分页
                        });
                        break;
                    case 'AddData':
                        var buttonEle = button.load({ elem: this });
                        var msgTitle = '@L("新增数据")'
                        console.log('新增数据');
                        GetViewHtml('/DaTi/D_Gift/RenderViewToString', 'AddOrEdit', [], function (html) {
                            layer.open({
                                title: msgTitle,
                                type: 1,
                                area: ['40%', '60%'],
                                content: html,
                                success: function (layero, index, that) {
                                    G_LayuiOpenTypeIndex = index;
                                },
                                end: function (index, layero) {
                                    // 这里写关闭窗口后需要执行的代码
                                    console.log('窗口被关闭了End');
                                    reloadTableData();
                                },
                            });
                            buttonEle.stop();
                        })
                        break;
                    case 'DelData':
                        var data = checkStatus.data;
                        //obj.del(); // 删除对应行（tr）的DOM结构
                        console.log(data)
                        if (data.length >= 1) {
                            var msgTitle = '@L("确定删除选中的数据吗?")'
                            layer.confirm(msgTitle,{ title:'@L("信息")',btn: ['@L("确认")', '@L("取消")']}, function (index) {
                                var Ids = [];
                                for (var i in data) {
                                    Ids.push(data[i].Id)
                                }
                                DelBatchData(Ids)
                                layer.close(index);
                            });

                        } else {
                            var msgTitle = '@L("请选择要删除的数据")'
                            layer.alert(msgTitle);
                        }
                        break;
                    case 'ExportExcelData':
                        Exporte();
                        break;
                    case 'LAYTABLE_TIPS':
                        layer.alert('自定义工具栏图标按钮');
                        break;
                };
            });
            // 表头自定义元素工具事件 --- 2.8.8+
            table.on('colTool(tableEle_@randomId)', function (obj) {
                var event = obj.event;
                console.log(obj);
                if (event === 'email-tips') {
                    layer.alert(layui.util.escape(JSON.stringify(obj.col)), {
                        title: '当前列属性配置项'
                    });
                }
            });

            // 触发单元格工具事件
            table.on('tool(tableEle_@randomId)', function (obj) { // 双击 toolDouble
                var data = obj.data; // 获得当前行数据
                if (obj.event === 'edit') {
                    var buttonEle = button.load({ elem: this });
                    var msgTitle = '@L("编辑")【' + data.Name + '】';
                    GetViewHtml('/DaTi/D_Gift/RenderViewToString', 'AddOrEdit', [data.Id], function (html) {
                        layer.open({
                            title: msgTitle,
                            type: 1,
                            area: ['40%', '60%'],
                            content: html,
                            success: function (layero, index, that) {
                                G_LayuiOpenTypeIndex = index;
                            },
                            end: function (index, layero) {
                                // 这里写关闭窗口后需要执行的代码
                                console.log('窗口被关闭了End');
                                reloadTableData();
                            },
                        });
                        buttonEle.stop();
                    })

                } else if (obj.event === 'more') {
                    var dataDrop=[];
                    dataDrop.push({
                            title: '@L("查看")',
                            id: 'detail'
                        })
                    if(IsPermission('GeneralDelDataPerm')){
                        dataDrop.push( {
                            title: '@L("删除")',
                            id: 'del'
                        })
                    }
                    // 更多 - 下拉菜单
                    dropdown.render({
                        elem: this, // 触发事件的 DOM 对象
                        show: true, // 外部事件触发即显示
                        data:dataDrop,
                        click: function (Data) {
                            if (Data.id === 'detail') {
                                //layer.msg('查看操作，当前行 ID:' + data.id);
                                var msg = '@L("当前列数据")'
                                layer.alert(layui.util.escape(JSON.stringify(data)), {
                                    title: msg
                                    ,btn: ['@L("确认")']
                                });
                            } else if (Data.id === 'del') {
                                var msg = '@L("确认删除行")';
                                layer.confirm(msg + ' [' + data.Name + '] ?',{ title:'@L("信息")',btn: ['@L("确认")', '@L("取消")']}, function (index) {
                                    obj.del(); // 删除对应行（tr）的DOM结构
                                    DelData(data.Id);
                                    layer.close(index);
                                });
                            }
                        },
                        align: 'right', // 右对齐弹出
                        style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' // 设置额外样式
                    })
                }
            });

            // 触发表格复选框选择
            table.on('checkbox(tableEle_@randomId)', function (obj) {
                console.log(obj)
            });

            // 触发表格单选框选择
            table.on('radio(tableEle_@randomId)', function (obj) {
                console.log(obj)
            });

            // 行单击事件
            table.on('row(tableEle_@randomId)', function (obj) {
                //console.log(obj);
                //layer.closeAll('tips');
            });
            // 行双击事件
            table.on('rowDouble(tableEle_@randomId)', function (obj) {
                console.log(obj);
            });



            // 单元格编辑事件
            table.on('edit(tableEle_@randomId)', function (obj) {
                var field = obj.field; // 得到字段
                var value = obj.value; // 得到修改后的值
                var data = obj.data; // 得到所在行所有键值
            });


            function DelData(Id) {
                var formData = {
                    Id: Id
                };
                $.ajax({
                    type: 'POST',
                    url: '/api/D_Gift/Delete',//发送请求
                    data: formData,
                    success: function (result) {
                        console.log(result)
                        if (result.Succeeded) {
                                toast.success({
                                    message: '@L("删除成功")',
                                });
                                reloadTableData()
                        } else {
                            toast.error({
                                message: '@L("删除失败")',
                            });
                        }
                    }
                });
            }
            function DelBatchData(Ids) {
                var formData = {
                    Ids: Ids
                };
                $.ajax({
                    type: 'POST',
                    url: '/api/D_Gift/DeleteBatch',//发送请求
                    data: formData,
                    success: function (result) {
                        console.log(result)
                        if (result.Succeeded) {
                            toast.success({
                                message: '@L("删除成功")',
                            });
                            reloadTableData()
                        } else {
                            toast.error({
                                message: '@L("删除失败")',
                            });
                        }
                    }
                });
            }

            function GetProgressPercent(key,ele,IsCancel=false) {
                console.log("-GetProgressPercent-")
                var formData = {
                    key: key,
                    IsCancel: IsCancel
                };
                $.ajax({
                    type: 'POST',
                    url: '/api/D_Gift/GetProgressPercent',//发送请求
                    data: formData,
                    success: function (result) {
                        console.log(result)
                        if (result.Data != "100") {
                            var titleMsg = '@L("导入中")';
                            $("#progressMsg").html(titleMsg)
                        }

                        element.progress(ele, parseInt(result.Data)+"%")
                      
                    }
                });
            }
            function Exporte(){
                var key = $("#Querykey_@randomId").val();

                window.location = "/api/D_Gift/ExPortExcel?key=" + key;
            }

            function reloadTableData() {
                var key = $("#Querykey_@randomId").val();
                table.reloadData('tableEle_@randomId', {
                    where: {
                        key: key,
                    },
                });
            }


        });

    </script>

}